/*
 * Trie.cpp
 *
 *  Created on: 23/10/2011
 *      Author: diego
 */

#include "Trie.h"

Trie::Trie() {
	int i;
	for (i = 0; i < 36; i++){
		this->raiz[i] = NULL;
	}
}

size_t Trie::posicion(char c){
	if (c <= 57 && c >= 48){
		// es un numero
		return c - 48;
	}else if (c <= 122 && c >= 97){
		// es una minuscula
		return 10 + (c - 97);
	}

	return -1;
}

void Trie::insertar(string termino){
	//cout << termino << endl;
	size_t size = termino.length();
	if (size < 1){
		// es un termino vacio
		return;
	}

	char c = termino[0];
	int pos = this->posicion(c);
	//cout << pos << endl;

	if (this->raiz[pos] == NULL){
		NodoTrie* nodo = new NodoTrie(termino[0]);
		this->raiz[pos] = nodo;
	}

	this->raiz[pos]->insertar(termino, 1);
}

bool Trie::buscar(string termino){
	size_t size = termino.length();

	if (size < 1){
		// es un termino vacio
		return false;
	}

	char c = termino[0];
	int pos = this->posicion(c);
	if (pos < 0){
		return false; //es un caracter no valido de stopword
	}

	if (this->raiz[pos] == NULL){
		return false;
	}else{
		return this->raiz[pos]->buscar(termino, 1);
	}
}

char Trie::getChar(int pos){
	if (pos >= 0 && pos <= 9){
		return (char) pos + 57;
	}else if (pos >=10 && pos <= 35){
		return (char) (pos - 10) + 97;
	}
}

void Trie::grabarArbol(ofstream* fd){
	int i;
	string termino = "";
	for (i = 0; i < 36; i++){
		if (this->raiz[i] != NULL){
			this->raiz[i]->grabar(fd, termino);
		}
	}
}

Trie::~Trie() {
	int i;
	for (i = 0; i < 36; i++){
		delete this->raiz[i];
	}
}

